package com.nowcoder.community.controller;

import com.nowcoder.community.contant.Entity;
import com.nowcoder.community.contant.Topic;
import com.nowcoder.community.entity.*;
import com.nowcoder.community.event.EventProducer;
import com.nowcoder.community.repository.CommentMapper;
import com.nowcoder.community.service.DisccusPostService;
import com.nowcoder.community.service.LikeService;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.utils.CommunityUtils;
import com.nowcoder.community.utils.HostHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Controller
@RequestMapping("/discuss")
@Slf4j
public class DiscussPostController {

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private DisccusPostService disccusPostService;

    @Autowired
    private UserService userService;

    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private LikeService likeService;

    @Autowired
    private EventProducer eventProducer;

    @PostMapping("/add")
    @ResponseBody
    public String addDiscussPost(String title, String content){
        User user = hostHolder.getUser();
        if (user == null)
            return CommunityUtils.getJsonString(403, "用户未登录");

        if (StringUtils.isBlank(title) || StringUtils.isBlank(content)){
            return CommunityUtils.getJsonString(400, "标题或内容不能为空" );
        }

        // 添加帖子
        DiscussPost post = new DiscussPost();
        post.setUserId(user.getId());
        post.setTitle(title);
        post.setContent(content);
        post.setCreateTime(new Date());
        disccusPostService.addDiscussPost(post);

        //将帖子添加到 es
        Event event = new Event()
                .setEntityType(Entity.DISCUSS_POST)
                .setEntityId(post.getId())
                .setTopic(Topic.POST_PUBLISH);
        eventProducer.fireEvent(event);

        // 跟新帖子分数
        disccusPostService.refreshScore(post.getId());
        return CommunityUtils.getJsonString(200, "帖子发布成功");
    }

    @GetMapping("/detail/{discussPostId}")
    public String getDiscussPostDetail(@PathVariable int discussPostId, Model model, Page page){
        // 帖子详情
        DiscussPost post = disccusPostService.findDiscussPostById(discussPostId);
        User user = userService.findUserById(post.getUserId());
        model.addAttribute("post", post);
        model.addAttribute("user", user);
        // 帖子的赞
        model.addAttribute("likeCount", likeService.countEntityLikes(Entity.DISCUSS_POST, post.getId()));
        model.addAttribute("likeStatus", hostHolder.getUser() == null ? 0 : likeService.likeStatus(hostHolder.getUser().getId(), Entity.DISCUSS_POST, post.getId()));

        // 帖子评论
        page.setLimit(5);
        page.setRows(post.getCommentCount());
        page.setPath("/discuss/detail/" + discussPostId);
        List<Comment> comments = commentMapper.selectCommentsByEntity(Entity.DISCUSS_POST, discussPostId, page.getOffset(), page.getLimit());
        List<Map<String, Object>> commentVO = new LinkedList<>(); // view obj
        for (Comment comment: comments){
            // 对每条评论进行处理
            Map<String, Object> commentMap = commentProcess(comment);
            // 取出评论的回复并进行处理
            List<Comment> replys = commentMapper.selectCommentsByEntity(Entity.COMMENT, comment.getId(), 0, Integer.MAX_VALUE);
            commentMap.put("replys", replys.stream().map(this::commentProcess).toArray());
            commentMap.put("replyCount", commentMapper.countCommentsByEntity(Entity.COMMENT, comment.getId()));
            commentVO.add(commentMap);
    }
        model.addAttribute("comments", commentVO);
        model.addAttribute("commentCount", commentMapper.countCommentsByEntity(Entity.DISCUSS_POST, discussPostId));
        return "/site/discuss-detail";
    }

    private Map<String, Object> commentProcess(Comment comment){
        // 处理评论，从数据库中取出评论涉及的作者和目标用户
        Map<String, Object> map = new HashMap<>();
        map.put("comment", comment);
        map.put("author", userService.findUserById(comment.getUserId()));
        int targetId = comment.getTargetId();
        map.put("target", targetId != 0 ? userService.findUserById(targetId) : null);
        // 赞
        map.put("likeCount", likeService.countEntityLikes(Entity.COMMENT, comment.getId()));
        map.put("likeStatus", hostHolder.getUser() == null ? 0 : likeService.likeStatus(hostHolder.getUser().getId(), Entity.COMMENT, comment.getId()));
        return map;
    }

    /**
     * 顶置功能
     */
    @PostMapping("/top")
    @ResponseBody
    public String top(int id){
        disccusPostService.updateType(id, 1);
        // 更新 es
        Event event = new Event()
                .setTopic(Topic.POST_PUBLISH)
                .setEntityType(Entity.DISCUSS_POST)
                .setEntityId(id);
        eventProducer.fireEvent(event);
        return CommunityUtils.getJsonString(200, "顶置成功");
    }

    /**
     * 加精功能
     * */
    @PostMapping("/wonderful")
    @ResponseBody
    public String wonderful(int id){
        disccusPostService.updateStatus(id,1);
        // 更新es
        Event event = new Event()
                .setTopic(Topic.POST_PUBLISH)
                .setEntityType(Entity.DISCUSS_POST)
                .setEntityId(id);
        eventProducer.fireEvent(event);

        // 更新帖子分数
        disccusPostService.refreshScore(id);
        return CommunityUtils.getJsonString(200,"加精成功");
    }

    /**
     * 删帖功能
     * */
    @PostMapping("/delete")
    @ResponseBody
    public String delete(int id){
        disccusPostService.updateStatus(id,2);
        // 删除es中的帖子
        Event event = new Event()
                .setTopic(Topic.POST_DELETE)
                .setEntityType(Entity.DISCUSS_POST)
                .setEntityId(id);
        eventProducer.fireEvent(event);
        return CommunityUtils.getJsonString(200, "删帖成功");
    }
}
